const fs   = require('fs')
const path = require('path')
const {readJson,writeJson} = require('../../until/fs');
const {USER_JSON} = require('../../config/config.data');
const uuid = require('node-uuid')

let uploadAvatar = (req,res)=>{

    const {fieldname,originalname} = req.files[0];

    // 创建一个我们喜欢的新路径
    const newName = 'public/avatar/'+fieldname+path.parse(originalname).ext;

    // 重写图片路径
    fs.rename(req.files[0].path,newName,function(err){
        if(err){
            res.send({code:0,msg:'上传失败'})
        }else{
            // 读用户数据
            let userData = readJson(USER_JSON);
            // 查找
            let index = userData.findIndex(item=>item.user ===fieldname)
            // 判断是否存在该用户
            if(index===-1){
                res.send({code:0,msg:'用户头像更新失败'})
                return
            }
            // 修改路径
            userData[index].img = '/'+newName;
            // 重写数据
            writeJson(USER_JSON,userData)

            res.send({code:1,msg:'上传成功',data:'/'+newName+'?'+uuid.v1()})
        }
    })

}

module.exports = {uploadAvatar}